/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import Entity.*;
import Model.DaftarDosenPeneliti;
import Model.DaftarPenelitian;
import Model.DaftarSumberPendanaan;
import Model.DosenModel;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author user
 */
public class UbahPenelitian extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        HttpSession session = request.getSession();
        String idUser = (String) session.getAttribute("id_user");

        ArrayList ListRole = new ArrayList();
        ListRole = (ArrayList) session.getAttribute("role");

        boolean bukanRole = true;
        if (session.getAttribute("role") != null) {
            for (int i = 0; i < ListRole.size(); i++) {
                if (ListRole.get(i).equals("dosen")) {
                    bukanRole = false;
                }
            }
        }

        if (session.getAttribute("role") == null) {
            Login servlet = new Login();
            servlet.processRequest(request, response);
        } else if (bukanRole) {
            request.setAttribute("menu", "home");
            request.setAttribute("submenu", "");
            RequestDispatcher dis = request.getRequestDispatcher("AccessDenied.jsp");
            dis.forward(request, response);
        } else {

            Penelitian penelitian = new Penelitian();
            Penelitian penelitianLama = new Penelitian();
            DaftarPenelitian daftarPenelitian = new DaftarPenelitian();

            int noPenelitian = Integer.parseInt(request.getParameter("noPenelitian"));
            penelitianLama.setNoPenelitian(noPenelitian);
            penelitianLama = daftarPenelitian.detailPenelitian(penelitianLama);

            penelitian.setNoPenelitian(noPenelitian);

            String status = "";
            if (request.getParameter("status") != null) {
                status = request.getParameter("status");
            }

            if (status.equals("submit")) {
                String[] array = new String[5];

                Calendar c = Calendar.getInstance();
                c.setTime(new Date());
                //String d = + "-"+c.MONTH+"-"+c.DATE;
                int Month = c.get(Calendar.MONTH) + 1;
                String tanggal = c.get(Calendar.DATE) + "" + Month + "" + c.get(Calendar.YEAR) + "_" + c.get(Calendar.HOUR_OF_DAY) + "" + c.get(Calendar.MINUTE);

                try {
                    PrintWriter out = response.getWriter();

                    // Check that we have a file upload request

                    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

                    // Create a factory for disk-based file items  
                    DiskFileItemFactory factory = new DiskFileItemFactory();

                    // Create a new file upload handler  
                    ServletFileUpload fileUpload = new ServletFileUpload(factory);

                    // Parse the request 
                    List items = fileUpload.parseRequest(request);
                    Iterator ir = items.iterator();
                    int count = 0;
                    while (ir.hasNext()) {
                        FileItem item = (FileItem) ir.next();
                        if (item.isFormField()) {
                            //mengambil data input yang selain file
                            out.print(item.getFieldName());
                            array[count] = item.getString();
                            count++;
                        } else {
                            if (item.getFieldName().equals("lap")) {
                                if (!item.getName().isEmpty()) {
                                    String nama = tanggal + "_" + item.getName();
                                    String location = "C:" + File.separator + "File" + File.separator + "Penelitian" + File.separator + "Laporan_Penelitian";
                                    String uploadFile = location + File.separator + nama;
                                    File file = new File(uploadFile);
                                    item.write(file);

                                    penelitian.setLampiranLaporan(nama);
                                    penelitian.setTanggalUploadLaporan(c.get(Calendar.YEAR) + "-" + Month + "-" + c.get(Calendar.DATE));
                                    penelitian.setTipeLampiranLaporan(item.getContentType());
                                    penelitian.setUkuranLampiranLaporan("" + item.getSize() + " KB");
                                } else {
                                    penelitian.setLampiranLaporan(penelitianLama.getLampiranLaporan());
                                    penelitian.setTanggalUploadLaporan(penelitianLama.getTanggalUploadLaporan());
                                    penelitian.setTipeLampiranLaporan(penelitianLama.getTipeLampiranLaporan());
                                    penelitian.setUkuranLampiranLaporan(penelitianLama.getUkuranLampiranLaporan());
                                }

                            }


                        }
                    }
                } catch (FileUploadException ex) {
                    log("Error encountered while parsing the request", ex);
                } catch (Exception ex) {
                    log("Error encountered while uploading file", ex);
                }

                SumberPendanaan dana = new SumberPendanaan();

                penelitian.setJudulPenelitian(array[0]);
                penelitian.setKetuaPeneliti(idUser);
                penelitian.setDanaDiterima(array[1].replace(".", ""));
                dana.setIdSumberPendanaan(Integer.parseInt(array[2]));
                penelitian.setTanggalPenelitianDimulai(array[3]);
                penelitian.setTanggalPenelitianSelesai(array[4]);

                penelitian.setSumberDana(dana);
                penelitian.setStatusPenelitian("0");
                User userPengupload = new User();
                userPengupload.setIdUser(idUser);
                penelitian.setPengupload(userPengupload);

                boolean sukses = daftarPenelitian.ubahDataPenelitian(penelitian);
                String pesan;
                String isiPesan;
                if (sukses) {

                    DosenPeneliti ketuaPeneliti = new DosenPeneliti();
                    DaftarDosenPeneliti ModelDosenPeneliti = new DaftarDosenPeneliti();

                    User user = new User();
                    user.setIdUser(penelitian.getKetuaPeneliti());

                    Dosen dosen = new Dosen();
                    dosen.setUser(user);

                    ketuaPeneliti.setStatusDosen("1");
                    ketuaPeneliti.setPenelitian(penelitian);
                    ketuaPeneliti.setDosen(dosen);

                    ModelDosenPeneliti.ubahTimDosenPPM(ketuaPeneliti);

                    pesan = "sukses";
                    isiPesan = "Data penelitian berhasil diubah";
                } else {
                    pesan = "gagal";
                    isiPesan = "Pengubahan data penelitian tidak berhasil";
                }

                request.setAttribute("pesan", pesan);
                request.setAttribute("isiPesan", isiPesan);
                TampilDaftarPenelitian servlet = new TampilDaftarPenelitian();
                servlet.processRequest(request, response);

            } else {
                

                List<SumberPendanaan> listSumberDana = new ArrayList<SumberPendanaan>();
                DaftarSumberPendanaan modelSumberPendanaan = new DaftarSumberPendanaan();

                listSumberDana = modelSumberPendanaan.ambilDaftarSumberDana();

                List<Dosen> listDosen = new ArrayList();
                DosenModel dosenModel = new DosenModel();

                listDosen = dosenModel.DaftarDosen();

                request.setAttribute("penelitian", penelitianLama);
                request.setAttribute("dana", listSumberDana);
                request.setAttribute("dosen", listDosen);
                request.setAttribute("menu", "ppm");
                request.setAttribute("submenu", "penelitian");

                RequestDispatcher dis = request.getRequestDispatcher("ppm/halamanUbahPenelitian.jsp");
                dis.forward(request, response);
            }
        }

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
